package com.gzs.learn.admin.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gzs.learn.admin.common.constant.AdminConstants;
import com.gzs.learn.admin.common.core.page.PageDomain;
import com.gzs.learn.admin.common.utils.ServletUtils;
import com.gzs.learn.inf.PageResponseDto;
import com.gzs.learn.inf.PageResponseDto.PageResponse;

import java.util.List;

/**
 * 表格数据处理
 *
 * @author guanzhisong
 */

public class PageUtil {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
        pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        return pageDomain;
    }

    public static PageDomain buildPageRequest() {
        return getPageDomain();
    }

    public static Page<?> getPage() {
        Integer page = ServletUtils.getParameterToInt(PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
        page = (page == null || page <= 0) ? 1 : page;
        pageSize = (pageSize == null || pageSize <= 0) ? 10 : pageSize;
        Page<?> pageParam = new Page<>(page, pageSize);
        return pageParam;
    }

    /**
     * 默认的最大页面参数
     *
     * @return
     */
    public static Page<?> getMaxPageParam() {
        return new Page<>(1, AdminConstants.MAX_RECORDS_LIMIT);
    }

    public static <T> PageResponseDto<T> buildPageResponse(IPage<T> pageInfo) {
        if (pageInfo.getTotal() == 0) {
            return PageResponseDto.success(Lists.newArrayList(), PageResponse.getNullPage());
        }
        List<T> records = pageInfo.getRecords();
        PageResponse page = PageResponse.builder().page((int) pageInfo.getCurrent()).pageSize((int) pageInfo.getSize())
                .total((int) pageInfo.getTotal()).build();
        return PageResponseDto.success(records, page);
    }
}
